require "digest/sha1"
class User < ActiveRecord::Base
  #  在数据库中没有纯文本的密码，
  #  attr_accessor来创建一个可读/写的model属性。
  attr_accessor :password

  attr_accessible :name, :password
  validates_uniqueness_of :name
  validates_presence_of :name, :password

#  def self.authenticate(name, password)
#    user = self.find_by_name(name)
#    if user
#      expected_password = encrypted_password(password, user.salt)
#      if user.hashed_password != expected_password
#        user = nil
#      end
#    end
#    user
#  end


  def self.login(name, password)
    hashed_password = hash_password(password || "")
    find(:first,
      :conditions => ["name = ? and hashed_password = ?",
        name, hashed_password])
  end
  
  def try_to_login
    User.login(self.name, self.password)
#    User.find_by_name_and_hashed_password(name, "")
  end
  
  def before_create
    self.hashed_password = User.hash_password(self.password)
  end

  before_destroy :dont_destroy_dave
  def dont_destroy_dave
    raise "Can't destroy dave" if self.name == 'dave'
  end
  
  def after_create
    @password = nil
  end
  
  private
  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end

end
